package edu.biwu.servlet;

import edu.biwu.bin.User;
import edu.biwu.utils.JDBCUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取浏览器发送的参数
        //request.getParameter()获取指定参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        /*System.out.println(username + " " + password);*/

        //2.利用DbUtils以及页面传递的username和password去数据库中查询
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

        User user = null;
        try{
            user = qr.query("SELECT * FROM `user` WHERE username=? AND `password`=?",
                    new BeanHandler<>(User.class),
                    username,password);
        }catch(SQLException e){
            throw new RuntimeException(e);
        }

        //3.根据user来判断最终结果
        //a.如果user为null，说明在数据库中没有找到该用户（用户不存在或用户错误），响应给浏览器login fail
        //b.如果user不为null，说明在数据库查找到该用户，响应给浏览器login success
        if (user == null){
            response.getWriter().write("login fail");
        }else {
            response.getWriter().write("login success");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
